<template>
  <div class="">
    <!-- 封装 input  组件可以使用 v-model  -->
    <MyInput @blur="SearchValue" v-model="search"></MyInput>

    <!-- 历史记录 -->
    <div v-if="$store.state.objList.length && obj.length == 0" class="history">
      <header>
        <p>历史记录</p>
        <p style="color:red;" @click="$store.commit('removeAll')">全部删除</p>
      </header>
      <ul>
        <li
          @click="searchPushValue(v)"
          v-for="(v, i) in $store.state.objList"
          :key="i"
        >
          <span>{{ v }}</span>
          <b @click.stop="$store.commit('remove', i)">X</b>
        </li>
      </ul>
    </div>
    <!-- 内容展示部分 -->
    <ul v-else>
      <li
        @click="$router.push('/detalis?id=' + v.goods_id)"
        v-for="(v, i) in obj"
        :key="i"
      >
        {{ v.goods_name }}
      </li>
    </ul>
  </div>
</template>

<script>
import MyInput from "../components/myInput.vue";
import axios from "axios";
import { ref } from "vue";
import { useStore } from "vuex";
export default {
  setup() {
    let obj = ref([]);
    let search = ref();
    let store = useStore();
    function SearchValue() {
      axios
        .get(
          `https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch?query=${search.value}`
        )
        .then((res) => {
          obj.value = res.data.message;
          console.log(obj.value);
        });

      // 把输入框的值发给 vuex
      store.commit("pushList", search.value);
    }
    // 搜索
    function searchPushValue(v) {
      search.value = v;
      SearchValue();
    }
    return { obj, SearchValue, search, searchPushValue };
  },
  components: { MyInput },
};
</script>

<style lang="scss" scoped>
ul {
  width: 100%;
  height: 100%;
  li {
    margin: 10px 0;
  }
}
.history {
  width: 100%;
  header {
    display: flex;
    width: 100%;
    height: 40px;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
  }
  ul {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    li {
      border: 1px solid #000;
      padding: 10px 20px;
      margin: 5px;
      list-style: none;
      border-radius: 15px;

      b {
        margin-left: 20px;
      }
    }
  }
}
</style>
